package com.lst.demo.ui;


import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andrognito.patternlockview.PatternLockView;
import com.andrognito.patternlockview.listener.PatternLockViewListener;
import com.andrognito.patternlockview.utils.PatternLockUtils;
import com.andrognito.patternlockview.utils.ResourceUtils;
import com.andrognito.rxpatternlockview.RxPatternLockView;
import com.andrognito.rxpatternlockview.events.PatternLockCompleteEvent;
import com.andrognito.rxpatternlockview.events.PatternLockCompoundEvent;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lst.demo.R;

import java.util.List;

import io.reactivex.functions.Consumer;

public class LockViewSetActivity extends AppCompatActivity {

    private PatternLockView mPatternLockView;
    private TextView tvProfileName;
    private TextView tvProfileInfo;
    private LinearLayout llBottom;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_set_lock_view);

        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)//设置状态栏颜色为白色
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .navigationBarColor(R.color.white)
                .navigationBarDarkIcon(true)
                .init();

        //获取控件对象
        mPatternLockView = (PatternLockView) findViewById(R.id.patter_lock_view);

        tvProfileName = findViewById(R.id.profile_name);

        tvProfileInfo = findViewById(R.id.profile_info);

        llBottom = findViewById(R.id.ll_bottom);

        SPUtils.getInstance().remove("firstlockpaswd");
        SPUtils.getInstance().remove("confirmlockpaswd");


        //返回
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SPUtils.getInstance().remove("firstlockpaswd");
                SPUtils.getInstance().remove("confirmlockpaswd");

                finish();
            }
        });

        //重绘
        findViewById(R.id.tv_reset).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SPUtils.getInstance().remove("firstlockpaswd");
                SPUtils.getInstance().remove("confirmlockpaswd");

                tvProfileInfo.setText("绘制解锁图案,请至少连接4个点");
                mPatternLockView.clearPattern();
                llBottom.setVisibility(View.INVISIBLE);

                mPatternLockView.setEnabled(true);
            }

        });

        //确认
        findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String confirmlockpaswd = SPUtils.getInstance().getString("confirmlockpaswd");
                if (TextUtils.isEmpty(confirmlockpaswd)) {
                    ToastUtils.showLong("请再次绘制图案进行确认");
                    return;
                }
                SPUtils.getInstance().put("lockpaswd", confirmlockpaswd);
                //  ToastUtils.showLong("手势密码设置成功");
                finish();
            }

        });

        // mPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);       // 设置当前视图更多
//        mPatternLockView.setInStealthMode(true);                                     // 将模式设置为隐藏模式（隐藏模式绘图）
        mPatternLockView.setTactileFeedbackEnabled(true);                            //绘制图案时启用振动反馈
//        mPatternLockView.setInputEnabled(false);                                     //完全禁用模式锁定视图中的任何输入
//        mPatternLockView.setDotCount(3);
//        mPatternLockView.setDotNormalSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_size));
//        mPatternLockView.setDotSelectedSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_selected_size));
//        mPatternLockView.setPathWidth((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_path_width));
//        mPatternLockView.setAspectRatioEnabled(true);
//        mPatternLockView.setAspectRatio(PatternLockView.AspectRatio.ASPECT_RATIO_HEIGHT_BIAS);
//        mPatternLockView.setNormalStateColor(ResourceUtils.getColor(this, R.color.white));
//        mPatternLockView.setCorrectStateColor(ResourceUtils.getColor(this, R.color.primary));
//        mPatternLockView.setWrongStateColor(ResourceUtils.getColor(this, R.color.pomegranate));
//        mPatternLockView.setDotAnimationDuration(150);
//        mPatternLockView.setPathEndAnimationDuration(100);


        // n*n大小   3*3
        mPatternLockView.setDotCount(3);
        //没有点击时点的大小
      //  mPatternLockView.setDotNormalSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_size));
        //点击时点的大小
       // mPatternLockView.setDotSelectedSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_selected_size));
        //更改路径距离
      //  mPatternLockView.setPathWidth((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_path_width));

        mPatternLockView.setAspectRatioEnabled(true);
        mPatternLockView.setAspectRatio(PatternLockView.AspectRatio.ASPECT_RATIO_HEIGHT_BIAS);
        //mPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);
        mPatternLockView.setDotAnimationDuration(150);
        mPatternLockView.setPathEndAnimationDuration(100);
        mPatternLockView.setInStealthMode(false);
        mPatternLockView.setTactileFeedbackEnabled(true);
        mPatternLockView.setInputEnabled(true);
        mPatternLockView.addPatternLockListener(mPatternLockViewListener);


        RxPatternLockView.patternComplete(mPatternLockView)
                .subscribe(new Consumer<PatternLockCompleteEvent>() {
                    @Override
                    public void accept(PatternLockCompleteEvent patternLockCompleteEvent) throws Exception {
                        Log.d(getClass().getName(), "Complete: " + patternLockCompleteEvent.getPattern().toString());
                    }
                });

        RxPatternLockView.patternChanges(mPatternLockView)
                .subscribe(new Consumer<PatternLockCompoundEvent>() {
                    @Override
                    public void accept(PatternLockCompoundEvent event) throws Exception {
                        if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_STARTED) {
                            Log.d(getClass().getName(), "Pattern drawing started");
                        } else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_PROGRESS) {
                            Log.d(getClass().getName(), "Pattern progress: " +
                                    PatternLockUtils.patternToString(mPatternLockView, event.getPattern()));
                        } else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_COMPLETE) {
                            Log.d(getClass().getName(), "Pattern complete: " +
                                    PatternLockUtils.patternToString(mPatternLockView, event.getPattern()));
                        } else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_CLEARED) {
                            Log.d(getClass().getName(), "Pattern has been cleared");
                        }
                    }
                });

    }


    //设置监听器
    private PatternLockViewListener mPatternLockViewListener = new PatternLockViewListener() {
        @Override
        public void onStarted() {
            Log.d(getClass().getName(), "Pattern drawing started");
        }

        @Override
        public void onProgress(List<PatternLockView.Dot> progressPattern) {
            Log.d(getClass().getName(), "Pattern progress: " +
                    PatternLockUtils.patternToString(mPatternLockView, progressPattern));
        }

        @Override
        public void onComplete(List<PatternLockView.Dot> pattern) {
            Log.d(getClass().getName(), "Pattern complete: " +
                    PatternLockUtils.patternToString(mPatternLockView, pattern));

//            mPatternLockView.setViewMode(PatternLockView.PatternViewMode.AUTO_DRAW);


            //密码
            String patternToString = PatternLockUtils.patternToString(mPatternLockView, pattern);
            if (!TextUtils.isEmpty(patternToString)) {


                String firstlockpaswd = SPUtils.getInstance().getString("firstlockpaswd");

                if (TextUtils.isEmpty(firstlockpaswd)) {

                    //绘制图案少于4个点
                    if (patternToString.length() < 4) {
                        mPatternLockView.setViewMode(PatternLockView.PatternViewMode.WRONG);
                        tvProfileInfo.setText("至少需要连接4个点,请重试");

                        //1s后清除图案
                        delayclearPattern();

                    } else {

                        //第一次设置
                        SPUtils.getInstance().put("firstlockpaswd", patternToString);
                        tvProfileInfo.setText("再次绘制图案进行确认");
                        llBottom.setVisibility(View.VISIBLE);

                        //1s后清除图案
                        delayclearPattern();
                    }


                } else {


                    String confirmlockpaswd = SPUtils.getInstance().getString("confirmlockpaswd");

                    if (TextUtils.isEmpty(confirmlockpaswd)) {

                        if (patternToString.equals(firstlockpaswd)) {
                            //再次设置解锁图案
                            SPUtils.getInstance().put("confirmlockpaswd", patternToString);
                            tvProfileInfo.setText("解锁图案设置成功");
                            mPatternLockView.setEnabled(false);//设置成功之后,禁止再绘制,除非点击了重绘

                        } else {

                            tvProfileInfo.setText("请重试");
                            mPatternLockView.setViewMode(PatternLockView.PatternViewMode.WRONG);

                            //1s后清除图案
                            delayclearPattern();
                        }

                    }


                }


            }


        }

        @Override
        public void onCleared() {
            Log.d(getClass().getName(), "Pattern has been cleared");
        }
    };


    /**
     * 延迟1s清除绘制痕迹
     */
    private void delayclearPattern() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mPatternLockView.clearPattern();
            }
        }, 1000);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        SPUtils.getInstance().remove("firstlockpaswd");
        SPUtils.getInstance().remove("confirmlockpaswd");

    }

    @Override
    public void onBackPressed() {

        SPUtils.getInstance().remove("firstlockpaswd");
        SPUtils.getInstance().remove("confirmlockpaswd");

        super.onBackPressed();


    }
}